﻿namespace MicroCloud.Extensions
{
    /// <summary>
    /// 系统构建器辅助扩展方法
    /// </summary>
    public static class MicroCloudBuilderExtensions
    {
        internal static void InitConfiguration(this IServiceCollection services)
        {
            services.RemoveAll<IConfiguration>();          
            IConfiguration configuration = services.GetConfiguration();

            var env = services.GetHostEnvironment()?.EnvironmentName ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (configuration == null)
            {
                var builder = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory);
                #region 加载AppSettings文件夹
                var dir = Path.Combine(AppContext.BaseDirectory, PathConstants.AppSettings);
                if (Directory.Exists(dir))
                {
                    var appsettingsFiles = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly).ToList();
                    appsettingsFiles.ForEach(file =>
                    {
                        builder.AddJsonFile(file, optional: true, reloadOnChange: true);
                    });
                }
                #endregion

                #region 加载【appsettings】.json | 【appsettings】.【Env】.json 
                var appSettings = $"{PathConstants.AppSettings}.json";
                if (File.Exists(appSettings))
                {
                    builder.AddJsonFile(appSettings, optional: true, reloadOnChange: true);
                }

                
                var appsettingsEnv = $"{PathConstants.AppSettings}.{env}.json";
                if (File.Exists(appsettingsEnv))
                {
                    builder.AddJsonFile(appsettingsEnv, optional: true, reloadOnChange: true);
                }
                #endregion

                configuration = builder.Build();
            }

            if (configuration != null)
            {
                services.AddSingleton(configuration);
                Singleton<IConfiguration>.Instance = configuration;

                //监听配置文件更改后重新加载
                MicroCloudOptions Options = new();
                new MicroCloudOptionsSetup(configuration).Configure(Options);
                ChangeToken.OnChange(() => configuration.GetReloadToken(), (state) =>
                {
                    new MicroCloudOptionsSetup(configuration).Configure(Options);
                    //触发配置文件更改事件
                    var provider = services.BuildServiceProvider();
                    var eventBus = provider?.GetService<IEventBus>();
                    eventBus?.Publish(new ConfigurationChangeEventData(configuration));
                },env);
            }
        }

        internal static void InitLoggerFactory(this IServiceCollection services)
        {
            if (!services.Any(typeof(ILoggerFactory)))
            {
                services.AddLogging(opts =>
                {
#if DEBUG
                    opts.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
#else
                    opts.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
#endif
                });
            }
        }

        /// <summary>
        /// 添加核心模块
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        internal static IMicroCloudBuilder AddCorePack(this IMicroCloudBuilder builder)
        {
            builder.AddPack<CorePack>()
                .AddPack<DependencyPack>()
                .AddPack<EventBusPack>();

            return builder;
        }

    }
}